package visualcbir.util;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import javax.imageio.ImageIO;
import javax.media.jai.JAI;
import javax.media.jai.PlanarImage;

/**
 *
 * @author sheila
 */

public class VSUtils {
    static int defaultSize=120;

    public static String getProperty(String property){
        Properties oProperties = new Properties();
        try {
            FileInputStream fis  = new FileInputStream("./config/config.properties");
            oProperties.load(fis);
            String prop=oProperties.getProperty(property);
            fis.close();
            return prop;
        } catch (Exception ex) { System.out.println("Error on loadProperties "+ex.getLocalizedMessage());}
        return "-1";
    }

    public static Image readImage(String pstrFileName){
        PlanarImage planarImage = JAI.create("fileload", pstrFileName);
        planarImage.XToTileX(200);
        BufferedImage oBufferedImage = planarImage.getAsBufferedImage();
        return oBufferedImage;
    }

    public static Image readImageIO(String pstrFileName){
        BufferedImage img = null;
        try{   img = ImageIO.read(new File(pstrFileName));  }
        catch (Exception e) {System.out.println("VSUtils Error->"+e.getLocalizedMessage());        }
         return img;
    }

    /**
     * Normalize the Dimension to a newer one outsided by an square of side newSize
     * @param oldSize Dimension to be resized
     * @param newSize int that represents a side of an square that determine
     *          the new dimension.
     * @return the new Dimension whose width or heigth is newSize
     */
    public static Dimension normalizeSize(Dimension oldSize, int newSize){
         float dWidth = oldSize.width;
         float dHeigth = oldSize.height;
         float percentage = 1;

         if( dWidth > dHeigth ){
             percentage = newSize/dWidth;
             dWidth = newSize;
             dHeigth *= percentage;
         }
         else{
             percentage = newSize/dHeigth;
             dHeigth = newSize;
             dWidth *= percentage;
         }
        return new Dimension( Math.round(dWidth) , Math.round(dHeigth) );
     }


     /**
      * @param poBufferedImage
      * @param dScaleFactor: a Number between 0 and 1
      */
     public static Image setImageScaleFactor(Image poBufferedImage, double dScaleFactor){
         Dimension dim = normalizeSize(new Dimension(poBufferedImage.getWidth(null) , poBufferedImage.getHeight(null)) , defaultSize);
         if(dScaleFactor<0.01) dScaleFactor=0.01;         
         return poBufferedImage.getScaledInstance( (int)Math.round(dim.width*dScaleFactor), (int)Math.round(dim.height*dScaleFactor), Image.SCALE_FAST);
     }
     
     /**
      * @param poBufferedImage
      * @param dScaleFactor: a Number between 0 and 1
      * @return
      */
     public static Image getScaledImage( int iAvailableSpace, BufferedImage bImage){
         Dimension dim = normalizeSize(new Dimension(bImage.getWidth(null) , bImage.getHeight(null)), iAvailableSpace);
         return bImage.getScaledInstance( dim.width, dim.height, Image.SCALE_FAST);
     }

     public static double getRealImageScaleFactor(double dScaleFactor){         
         if(dScaleFactor<0.05) dScaleFactor=0.05;
         return defaultSize*dScaleFactor;
     }

     public static Point getCenterPoint(Container poContainer){
         return new Point(poContainer.getWidth()/2,poContainer.getHeight()/2);
     }
 
     public static void resetGraphics(Graphics g){
         g.setColor(Color.black);
         ((Graphics2D)g).setStroke(new BasicStroke(1.0f, BasicStroke.CAP_BUTT,BasicStroke.JOIN_MITER, 10.0f, null, 0.0f));
     }

    /*
     * Counts how many file or folders in the path respect the specified regex restriction.
     * It does not read recursively. Only shows the files and folders encountered in the given path.
     */
    public static String[] getFilesByRegex(String path, final String regex){
        String [] aFiles;
        File f=new File(path);
        aFiles = f.list(new FilenameFilter(){
            @Override
            public boolean accept(File dir, String name) {
                if(name.matches(regex)) return true;
                return false;
            }
        });
        return aFiles;
    }

    public static String[] orderNumericStrings(String[] names, String commonpart){
        List a = new ArrayList();
        for (int i = 0; i < names.length; i++) {
            String str = names[i];
            a.add( Integer.parseInt(str.substring( commonpart.length(), str.length()-5 )));
        }
        Collections.sort(a);
        for (int i = 0; i < names.length; i++) {
            names[i] = commonpart+ String.valueOf(a.get(i)) + ".jpeg";
        }
        return names;
    }

    public static int countFilesByRegex(String path, final String regex){
        return VSUtils.getFilesByRegex(path, regex).length;
    }

    public static void main(String[] args){
        //String[] afiles=VSUtils.getFilesByRegex("/home/sheila/NetBeansProjects/clusteringset-video/ClusterSet/Video2/Time1/Level2/Cluster3", "Object[0-9]+\\.jpeg|Center.jpeg");
        String[] afiles=VSUtils.getFilesByRegex("/home/sheila/NetBeansProjects/clusteringset-video/ClusterSet/Video2/Time1/Level2/", "Cluster[0-9]+");
        for (int i = 0; i < afiles.length; i++) {
            System.out.println("---->"+afiles[i]);
        }
        int images = VSUtils.countFilesByRegex("/home/sheila/NetBeansProjects/clusteringset-video/ClusterSet/Video2/Time1/Level2/", "Cluster[0-9]+");
        System.out.println("imgss" + images);
    }

}
